package com.lzlclass.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
public class uploadController {

    // 上传文件存储目录
    private static final String UPLOAD_DIRECTORY = "upload";


    @PostMapping("/upload")
    public Object doupload(HttpServletRequest request,
                           @RequestParam("name")String name,
                           @RequestParam("file") MultipartFile[] files ){

//        上传在服务器的真实路径
        String uploadPath = request.getServletContext().getRealPath(UPLOAD_DIRECTORY);
        System.out.println("上传路径："+uploadPath);
        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
       // 遍历上传的文件
        for (MultipartFile file : files){
            try{
                if(!file.isEmpty()){
                    // 拿到上传文件的文件名
                    String originalFilename = file.getOriginalFilename();
                    // 保存文件
                    file.transferTo(new File(uploadPath + File.separator+file.getOriginalFilename()));
                }
            } catch (IOException e) {
                System.out.println("上传异常："+e.getMessage());
                return e.getMessage();
            }

        }

        return "success";
    }


}